<template>
  <div class="print-preview-container">
    <!-- 工具栏 -->
    <PrintToolbar 
      :currentPage="currentPage"
      :totalPages="totalPages"
      @goBack="goBack"
      @showFormat="showFormatDialog = true"
      @print="print"
      @prevPage="prevPage"
      @nextPage="nextPage"
    />

    <!-- 预览区域 -->
    <div class="preview-area">
      <div class="page-container" ref="pageContainer">
        <PrintPage
          v-for="(pageContent, index) in paginatedContent"
          :key="index"
          :content="pageContent"
          :pageStyle="pageStyle"
          :contentStyle="contentStyle"
          :isCurrentPage="index + 1 === currentPage"
          :lineSpacing="formatSettings.lineSpacing"
          :pageNumber="index + 1"
          :totalPages="totalPages"
          :pageNumberPosition="formatSettings.pageNumberPosition"
          :pageNumberFormat="formatSettings.pageNumberFormat"
          :inquiredSignature="formatSettings.inquiredSignature"
          :inquiryCount="getInquiryCountSetting()"
          :inquiryCountFormat="getInquiryCountFormatSetting()"
          :inquiryCountData="inquiryCountData"
        />
      </div>
    </div>

    <!-- 格式设置对话框 -->
    <FormatDialog
      v-model:visible="showFormatDialog"
      :formatSettings="formatSettings"
      @reset="resetFormat"
      @cancel="showFormatDialog = false"
      @confirm="applyFormat"
    />
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import printJS from 'print-js'
import PrintToolbar from '../../components/print/PrintToolbar.vue'
import PrintPage from '../../components/print/PrintPage.vue'
import FormatDialog from '../../components/print/FormatDialog.vue'
import { usePagination } from '../../composables/usePagination.js'
import { PrintUtils } from '../../utils/printUtils.js'
import { generatePageStyles, generateCSSString } from '../../utils/printStyles.js'

const router = useRouter()
const route = useRoute()
const showFormatDialog = ref(false)
const currentPage = ref(1)
const totalPages = ref(1)
const pageContainer = ref(null)

// 格式设置
const formatSettings = reactive({
  category: 'admin',
  
  // 通用字段 - 三类都有的基础字段
  fontFamily: 'FangSong',
  fontSize: '14',
  lineSpacing: '10mm',
  blankLines: 'print',
  bottomLine: 'solid',
  contentIndent: '2',
  recordTime: 'print',
  pageNumberFormat: 'arabic',
  inquiredSignature: 'bottom_right',
  
  // 行政治安专有字段
  pageNumberPosition: 'top_right',
  witnessRecord: 'with_summons',
  inquiryCount: 'print',
  inquiryCountFormat: 'arabic',
  officerSignature: 'with_signature',
  recordHeaderFormat: '2012_combined',
  
  // 刑事专有字段
  criminalInquiryCount: 'print',
  criminalRecordHeader: '2012_combined',
  criminalInquiry: 'with_summons',
  
  // 交通事故专有字段
  accidentPagePosition: 'top_right',
  accidentPagePosition2: 'top_right',
  continuationSignature: 'inquired_person',
  accidentOfficerSignature: 'with_signature',
  accidentSummonsRecord: 'ministry_standard',
  accidentSummonsRecord2: 'with_tips',
  accidentSummonsRecord3: 'no_extension',
  
  // 当场盘查相关字段
  checkType: 'routine',
  checkLocation: 'street',
  checkBasis: 'routine_patrol',
  idCheck: 'id_card',
  questionResult: 'normal',
  
  // 林业询问相关字段
  forestryType: 'logging',
  forestLandType: 'state_owned',
  treeCategory: 'timber',
  cuttingPermit: 'with_permit',
  damageAssessment: 'minor',
  
  // 纪检调查相关字段
  talkType: 'discipline_investigation',
  violationType: 'political',
  investigationStage: 'preliminary',
  talkTarget: 'subject',
  confidentialLevel: 'general',
  
  // 其他通用格式设置（保持原有）
  timeFormat: 'western',
  lineHeight: '1.5',
  contentFormat: 'standard',
  expressionFormat: 'standard',
  titleLines: 2,
  pageMargin: '2.54',
  paragraphIndent: 2,
  pageObjectFormat: 'left',
  actualParagraphFormat: '2012combined'
})

// 从路由参数获取内容，如果没有则使用示例内容
const content = ref('')
const inquiryCountData = ref(null) // 存储询问次数数据

onMounted(async () => {
  const id = router.currentRoute.value.query.id
  let tableName = router.currentRoute.value.query.tableName
  if (id) {
    const data = await getDataById(tableName, id)
    if (data) {
      // 构建前置信息
      const headerInfo = PrintUtils.buildHeaderInfo(data)
      content.value = headerInfo + (data.blnr || '')
      // 获取询问次数数据
      inquiryCountData.value = data.cs || null
    } else {
      // 没有数据时显示示例格式
      const sampleData = {
        kssj_y: '', kssj_m: '', kssj_d: '', kssj_h: '', kssj_mi: '',
        jssj_y: '', jssj_m: '', jssj_d: '', jssj_h: '', jssj_mi: '',
        dd: '', xwr: '', xwrgzdw: '', jlr: '', jlrgzdw: '',
        bxwr: '', xb: '', nl: '', crrq: '', zjlx: '', zjhm: '',
        xzz: '', lxdh: '', hjzz: ''
      }
      const headerInfo = PrintUtils.buildHeaderInfo(sampleData)
      content.value = headerInfo + '在此输入笔录内容...'
      inquiryCountData.value = 1 // 示例数据
    }
  } else {
    // 没有ID时显示示例格式
    const sampleData = {
      kssj_y: '', kssj_m: '', kssj_d: '', kssj_h: '', kssj_mi: '',
      jssj_y: '', jssj_m: '', jssj_d: '', jssj_h: '', jssj_mi: '',
      dd: '', xwr: '', xwrgzdw: '', jlr: '', jlrgzdw: '',
      bxwr: '', xb: '', nl: '', crrq: '', zjlx: '', zjhm: '',
      xzz: '', lxdh: '', hjzz: ''
    }
    const headerInfo = PrintUtils.buildHeaderInfo(sampleData)
    content.value = headerInfo + '在此输入笔录内容...'
    inquiryCountData.value = 1 // 示例数据
  }
})

// 使用分页功能
const { paginateContent } = usePagination(formatSettings)

const paginatedContent = computed(() => {
  const pages = paginateContent(content.value)
  totalPages.value = pages.length || 1
  return pages
})

watch([
  () => content.value,
  () => formatSettings.fontSize,
  () => formatSettings.lineHeight,
  () => formatSettings.fontFamily,
  () => formatSettings.pageMargin,
  () => formatSettings.bottomLine
], () => {
  // 重新分页
  paginatedContent.value
})

// 页面样式 - 使用统一的样式生成函数
const pageStyle = computed(() => {
  const styles = generatePageStylesLocal(false)
  return styles.page
})

// 内容样式
const contentStyle = computed(() => ({
  textIndent: `${formatSettings.paragraphIndent}em`,
  fontSize: `${formatSettings.fontSize}pt`,
  lineHeight: formatSettings.lineHeight,
  fontFamily: formatSettings.fontFamily,
  textAlign: 'left'
}))

const goBack = () => {
  router.go(-1)
}

const prevPage = () => {
  if (currentPage.value > 1) {
    currentPage.value--
    scrollToPage()
  }
}

const nextPage = () => {
  if (currentPage.value < totalPages.value) {
    currentPage.value++
    scrollToPage()
  }
}

const scrollToPage = () => {
  const pageElement = pageContainer.value?.children[currentPage.value - 1]
  if (pageElement) {
    pageElement.scrollIntoView({ behavior: 'smooth', block: 'start' })
  }
}

// 统一的页面样式生成函数 - 使用共享工具
const generatePageStylesLocal = (forPrint = false) => {
  return generatePageStyles(formatSettings, forPrint)
}

// 统一的CSS样式字符串生成函数 - 使用共享工具  
const generateCSSStringLocal = (forPrint = false) => {
  return generateCSSString(formatSettings, forPrint)
}

const print = () => {
  // 直接使用预览页面的DOM结构进行打印，确保完全一致
  const pageElements = pageContainer.value?.children
  if (!pageElements || pageElements.length === 0) {
    console.error('没有找到预览页面')
    return
  }

  // 克隆所有页面元素
  const clonedPages = Array.from(pageElements).map((pageElement, index) => {
    const cloned = pageElement.cloneNode(true)
    
    // 应用统一的打印样式
    const printStyles = generatePageStylesLocal(true)
    Object.assign(cloned.style, {
      margin: printStyles.page.margin,
      width: printStyles.page.width,
      height: printStyles.page.height,
      boxShadow: printStyles.page.boxShadow,
      border: printStyles.page.border,
      position: printStyles.page.position,
      pageBreakAfter: index < pageElements.length - 1 ? 'always' : 'auto',
      pageBreakInside: 'avoid'
    })
    
    return cloned.outerHTML
  })

  const printContent = clonedPages.join('')

  printJS({
    printable: printContent,
    type: 'raw-html',
    style: generateCSSStringLocal(true)
  })
}

const applyFormat = () => {
  showFormatDialog.value = false
  console.log('Applied format settings:', formatSettings)
}

// 获取当前类别对应的询问次数设置
const getInquiryCountSetting = () => {
  switch (formatSettings.category) {
    case 'admin': // 行政治安
      return formatSettings.inquiryCount
    case 'criminal': // 刑事
      return formatSettings.criminalInquiryCount
    case 'traffic': // 交通事故
      return formatSettings.inquiryCount // 交通事故使用通用inquiryCount
    default:
      return formatSettings.inquiryCount
  }
}

// 获取当前类别对应的询问次数格式设置
const getInquiryCountFormatSetting = () => {
  // 所有类别都使用相同的格式设置
  return formatSettings.inquiryCountFormat
}

const resetFormat = () => {
  Object.assign(formatSettings, {
    category: 'admin',
    
    // 通用字段 - 三类都有的基础字段
    fontFamily: 'FangSong',
    fontSize: '14',
    lineSpacing: '10mm',
    blankLines: 'print',
    bottomLine: 'solid',
    contentIndent: '2',
    recordTime: 'print',
    pageNumberFormat: 'arabic',
    inquiredSignature: 'bottom_right',
    
    // 行政治安专有字段
    pageNumberPosition: 'top_right',
    witnessRecord: 'with_summons',
    inquiryCount: 'print',
    inquiryCountFormat: 'arabic',
    officerSignature: 'with_signature',
    recordHeaderFormat: '2012_combined',
    
    // 刑事专有字段
    criminalInquiryCount: 'print',
    criminalRecordHeader: '2012_combined',
    criminalInquiry: 'with_summons',
    
    // 交通事故专有字段
    accidentPagePosition: 'top_right',
    accidentPagePosition2: 'top_right',
    continuationSignature: 'inquired_person',
    accidentOfficerSignature: 'with_signature',
    accidentSummonsRecord: 'ministry_standard',
    accidentSummonsRecord2: 'with_tips',
    accidentSummonsRecord3: 'no_extension',
    
    // 当场盘查相关字段
    checkType: 'routine',
    checkLocation: 'street',
    checkBasis: 'routine_patrol',
    idCheck: 'id_card',
    questionResult: 'normal',
    
    // 林业询问相关字段
    forestryType: 'logging',
    forestLandType: 'state_owned',
    treeCategory: 'timber',
    cuttingPermit: 'with_permit',
    damageAssessment: 'minor',
    
    // 纪检调查相关字段
    talkType: 'discipline_investigation',
    violationType: 'political',
    investigationStage: 'preliminary',
    talkTarget: 'subject',
    confidentialLevel: 'general',
    
    // 其他通用格式设置（保持原有）
    timeFormat: 'western',
    lineHeight: '1.5',
    contentFormat: 'standard',
    expressionFormat: 'standard',
    titleLines: 2,
    pageMargin: '2.54',
    paragraphIndent: 2,
    pageObjectFormat: 'left',
    actualParagraphFormat: '2012combined'
  })
}

async function getDataById(tableName, id) {
  let res = await window.db.select(`select * from ${tableName} where id=${id}`)
  if (res.length == 0) {
    return null
  }
  return res[0]
}
</script>

<style scoped>
.print-preview-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  background-color: #f5f5f5;
  overflow: hidden;
}

.preview-area {
  flex: 1;
  overflow-y: auto;
  overflow-x: hidden;
  padding: 20px;
  height: 0;
}

.page-container {
  min-height: 100%;
}

/* 预览页面统一样式 - 与打印样式保持一致 */
:deep(.page) {
  border: 1px solid #ddd;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  transition: all 0.3s;
  position: relative;
}

:deep(.page.current-page) {
  border-color: #409eff;
  box-shadow: 0 6px 12px rgba(64, 158, 255, 0.2);
}

:deep(.page-content) {
  width: 100%;
  height: 100%;
  position: relative;
}

/* 记录行样式 - 与打印完全一致 */
:deep(.record-line) {
  display: block;
  width: 100%;
  box-sizing: border-box;
  text-align: left;
  padding-bottom: 2px;
}

:deep(.record-line.solid) {
  border-bottom: 1px solid #333;
}

:deep(.record-line.dashed) {
  border-bottom: 1px dashed #333;
}

:deep(.record-line.none) {
  border-bottom: none;
}

:deep(.record-line h3) {
  border-bottom: none !important;
  text-align: center;
  margin: 0;
  text-indent: 0 !important;
}

:deep(.record-line:empty::after) {
  content: " ";
  visibility: hidden;
}

:deep(p) {
  margin: 0;
  padding: 0;
}

:deep(h3) {
  text-align: center;
  margin: 0;
  border-bottom: none !important;
  text-indent: 0 !important;
}

/* 页码样式 */
:deep(.page-number) {
  position: absolute;
  font-size: 13px;
  color: #666;
  z-index: 10;
  background: rgba(255,255,255,0.8);
  padding: 2px 10px;
  border-radius: 4px;
  user-select: none;
}
:deep(.page-number-top-left) {
  top: 8px;
  left: 16px;
}
:deep(.page-number-top-right) {
  top: 8px;
  right: 16px;
}
:deep(.page-number-bottom-left) {
  bottom: 8px;
  left: 16px;
}
:deep(.page-number-bottom-right) {
  bottom: 8px;
  right: 16px;
}

/* 询问次数样式 */
:deep(.inquiry-count) {
  position: absolute;
  font-size: 13px;
  color: #666;
  z-index: 10;
  background: rgba(255,255,255,0.8);
  padding: 2px 10px;
  border-radius: 4px;
  user-select: none;
}
:deep(.inquiry-count-top-right) {
  top: 32px;
  right: 16px;
}

/* 签名栏样式 */
:deep(.signature-bar) {
  position: absolute;
  bottom: 24px;
  display: flex;
  font-size: 14px;
  color: #333;
  z-index: 10;
  align-items: center;
  pointer-events: none;
  user-select: none;
}
:deep(.signature-bottom-left) {
  left: 24px;
  right: 24px;
  justify-content: flex-start;
}
:deep(.signature-bottom-right) {
  right: 60px;
  width: 180px;
  justify-content: flex-end;
}
:deep(.signature-label) {
  min-width: 80px;
  flex-shrink: 0;
  margin-right: 12px;
}
:deep(.signature-flex-spacer) {
  flex: 1 1 auto;
}
:deep(.signature-date) {
  font-size: 13px;
  color: #666;
  min-width: 120px;
  text-align: right;
  letter-spacing: 2px;
}

/* 打印样式 */
@media print {
  .print-preview-container {
    height: auto;
  }

  .preview-area {
    padding: 0;
  }
}
</style>
